package com.banshuibao.bsb_android.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.adapter.MediaGrideListAdapter;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.MediaModel;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshBase;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshGridView;
import com.banshuibao.bsb_android.util.IntentManager;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by zyh on 2018/1/15.
 */

public class BuyMediaListActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener2<GridView> {

    private PullToRefreshGridView pullToRefreshGridView;

    private GridView gridView;

    private MediaGrideListAdapter adapter;

    private int sinceId = 1;

    private MediaModel.Data data;

    private ImageView background_iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy_media_list);

        initView();
    }

    private void initView() {
        setTitleText("已购视频");
        background_iv = findViewById(R.id.backgroud_iv);
        pullToRefreshGridView = findViewById(R.id.pull);
        pullToRefreshGridView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshGridView.setOnRefreshListener(this);
        gridView = pullToRefreshGridView.getRefreshableView();
        gridView.setNumColumns(2);
        Drawable drawable = getResources().getDrawable(R.drawable.noloading);
        ImageView imageView = new ImageView(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        imageView.setLayoutParams(params);
        imageView.setImageDrawable(drawable);
        gridView.setEmptyView(imageView);
        adapter = new MediaGrideListAdapter(this);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (adapter != null) {
                    MediaModel.Data data = adapter.getItem(i);
                    BuyMediaListActivity.this.data = data;
                    buyMedia(data);
                }
            }
        });
        loadNewData();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
        loadNewData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
        loadMedia(sinceId, sinceId + 10);
    }

    private void loadNewData() {
        if (adapter != null) {
            int end = adapter.getCount() > 10 ? adapter.getCount() : 10;
            sinceId = 1;
            loadMedia(sinceId, end);
        }
    }

    private void loadMedia(final int s, final int e) {
        MediaModel.Body body = new MediaModel.Body();
        body.setSinceId(s);
        body.setMaxId(e);
        body.setType("home");
        HttpUtil.doPost(Constants.Url.VIDEO_LIST, body, new HttpResponse(this, MediaModel.class) {
            @Override
            public void onResult(Object obj) {
                MediaModel mediaModel = (MediaModel) obj;
                sinceId += mediaModel.getRows();
                if (adapter != null) {
                    if (s == 1) {
                        adapter.setData(mediaModel.getData());
                    } else
                        adapter.addData(mediaModel.getData());
                }
                if (adapter != null && adapter.getCount() == 0) {
                    background_iv.setVisibility(View.VISIBLE);
                    pullToRefreshGridView.setVisibility(View.GONE);
                } else {
                    background_iv.setVisibility(View.GONE);
                    pullToRefreshGridView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                pullComplete();
            }
        });
    }

    private void buyMedia(final MediaModel.Data data) {
        MediaModel.BuyBody buyBody = new MediaModel.BuyBody();
        buyBody.setUuid(data.getId());
        HttpUtil.doPost(Constants.Url.IS_BUY, buyBody, new HttpResponse(this) {
            @Override
            public void onResult(Object obj) {
                JSONObject jsonObject = null;
                JSONObject jsonObject1 = null;
                try {
                    jsonObject = new JSONObject((String) obj);
                    jsonObject1 = jsonObject.getJSONObject("data");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (jsonObject1 != null) {
                    String type = jsonObject1.optString("type");
                    String vid = jsonObject1.optString("vid");
                    if ("0".equals(type) && !TextUtils.isEmpty(vid)) {
                        IntentManager.goMediaPlayActivity(BuyMediaListActivity.this, vid, Constants.Url.VIDEO, data.getId(), data.getImage());
                    } else {
                        new AlertDialog.Builder(BuyMediaListActivity.this).
                                setMessage("购买365会员可以免费观看所有视频,或者支付" + data.getPrice() + "元购买本集").
                                setPositiveButton("购买", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        IntentManager.goPayResultActivity(BuyMediaListActivity.this, data.getTitle(), String.valueOf(data.getPrice()), data.getId(), 4);
                                    }
                                }).setNegativeButton("取消", null).create().show();
                    }
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 200)
                buyMedia(BuyMediaListActivity.this.data);
        }
    }

    private void pullComplete() {
        pullToRefreshGridView.onRefreshComplete();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (adapter != null) {
            adapter.clear();
            adapter = null;
        }
    }
}
